<?php
	/**
	 * @author Nguyen Xuan Hong
	 * @copyright 2010
	 */

class clsForm
{
	
	# Private Input array
	var $input_array = array() ;
	
	# Javascript form check templates
	# This templates define javascript form check structure
	
	var $jsResource = '
	
		<script language = "javascript">
			///<!-CDB-FormFunction->
			
			function {form}FormCheck()
			{
				return {functionlist} true ;
			}
			
			///<!-CDE-FormFunction->
			///<!-CDB-ListFunction->
			
			function {form}{key}ObjecCheck()
			{
				// Get element object
				var jsfobject = $(\'#{key}\');
				var jsfinform = $(\'#div_support_{key}\');
				
				///<!-CDB-ElementCheck->
				
				if( {condition} )
				{
					//jsElementError(jsfobject,\'{messenger}\');
					jsfobject.addClass(\'ui-state-error\');	jsfinform.html(\'{messenger}\');jsfobject.focus();
					return false;
				}
				else  
				{
					jsfobject.removeClass(\'ui-state-error\');	jsfinform.html(\'\');
					//jsElementReset(jsfobject,\'{messenger}\');				
				}
				
				///<!-CDE-ElementCheck->
				
				return true ;
			}
			
			///<!-CDE-ListFunction->
		</script>
							';
		
	# Form html templates	
	# This templates define form structure and css
	var $formResource = '
<form method="post" action="{action}" onsubmit = "return {submitJS}" enctype="multipart/form-data">
	<table class="{class}" cellspacing="0" cellpadding="5" border = "0" style="{style}" id="{tbid}" width="auto">
		<tr>
			<td class="ui-dialog-titlebar ui-widget-header ui-corner-all" align="center" colspan="2"> {title} </td>
		</tr>
    	<!-- BOL - Header -->
		<tr>
			<td class="css_fheader" align="center" height="35px" colspan="2" valign = "bottom"> <br> {warn}</td>
		</tr>
        <!-- EOL - Header -->
		<tr>
			<td height = "15px" colspan = "3"></td>
		</tr>
        <!-- BOL - Lines -->
        <tr>
        	<td width="20%" align="right" style="padding:0px 5px;font-size:11px" rowspan="2">
            	<strong>{title}</strong> <br />
				<a style = "font-size:10px">{description}</a>
            </td> 
			<td style="padding:0px 10px" width="auto">
                {content}
			</td>
		</tr>
		<tr>
			<!--<td style = "font-size:10px" valign="top"  align="right" > {description}</td>	-->
            <td >
				<div id = \'div_support_{key}\'  style="margin-top:8px; margin-left:10px;">
				</div>
            </td>
        </tr>
        <!-- EOL - Lines -->
		<tr>
        	<td colspan = "2" align = "center">	
				<button class="ui-corner-all ui-mybutton" type="submit">{submitbtn}</button>
			</td>
		</tr>
</table>
</form>
							';
	
	# List function & List function Index
	# Store list needed function name for create main form check
	var $jsEIndex = 0 ;	
	var $jsElement = array();	
	
	var $redefineTemplates;
	
	var $icons = array(
		'null'	=>	'<span class="ui-icon-orange ui-icon-alert" style="margin: -2px 5px 0pt 0pt; float: left;" /> ',
		'max'	=>	'<span class="ui-icon-orange ui-icon-minus" style="margin: -2px 5px 0pt 0pt; float: left;" /> ',
		'min'	=>	'<span class="ui-icon-orange ui-icon-plus" style="margin: -2px 5px 0pt 0pt; float: left;" /> ',
		'num'	=>	'<span class="ui-icon-orange ui-icon-clipboard" style="margin: -2px 5px 0pt 0pt; float: left;" /> ',	
	);
	
	# Constructor
	# Default constructor get input array to class cache
	function clsForm($inp_array){
		$this->input_array = $inp_array ;
	}
	
	# GlobalJS
	# Store all body function javascript check valid input data
	var $globalJs;
	
	var $hasError = array();
	
	# Create form
	# @String <title>	@String <form name for js function name >	@Array <[action - name - value]>
	# ~ Return form and javascript content not inc jquery framework
	
	var $formname;
	
	function createForm($ftitle,$fname = 'autoform',$faction = '',$config = array()){
		if($config['fmresource']) {
			$this->formResource = $config['fmresource'];
		}
		$this->formname = $fname;
		
		
		if(!$this->redefineTemplates){
			// Autocreate form
			# WARN BLOCK	$warnBlock
			preg_match("#<!-- BOL - Header -->[\r\n]*(.*?)[\r\n]*<!-- EOL - Header -->#s",$this->formResource,$cache);
			$warnBlock = $cache[1];
			$warnBlock = ($this->hasError) ? str_replace('{warn}',$this->hasError['str'],$warnBlock) : '' ;
			
			# LINES BLOCK 
			preg_match("#<!-- BOL - Lines -->[\r\n]*(.*?)[\r\n]*<!-- EOL - Lines -->#s",$this->formResource,$cache);
			$linesBlock = $cache[0];
			
			$linesCode = '' ;					# new
		}else {
			$hredefcode = $this->redefineTemplates;
		}
		# @@@ Foreach all line element
		foreach($this->input_array as $key => $arr) { 
			$type	= $arr['type'];
			if(!$type) continue; 
			if (ereg("^function::*::*",$type)) {
				$ex_arr = split('::',$type);
				$str = $ex_arr[1]($$key);
				$type = 'function';
				//#FB::send("Funciton type");
			}
			$title	= $arr['title'];
			$desc 	= $arr['desc'];
			switch ($type) {
				case 'text'		: 
				case 'textarea'	: 
				case 'wysiwyg'	:
				case 'ckeditor'	:
				case 'time'	:		
				case 'ajaxSF'	:	
				case 'password'	: $elementCode = $this->eText($key); 	break;
				case 'imageupload'	: $elementCode = $this->eIMGUpload($key); 	break;	
				case 'videoupload'	: $elementCode = $this->eVIDEOUpload($key); 	break;
				case 'attachfile'	: $elementCode = $this->eAttach($key); 	break;	
				case 'function' : $elementCode = $str;				 	break;
				case 'radio'	: $elementCode = $this->eRadio($key);	break;
				case 'select'	: $elementCode = $this->eSelect($key);	break;
				case 'textauto'	: $elementCode = $this->eTextauto($key);	break;
				case 'check'	: $elementCode = $this->eCheck($key);	break;
				case 'title' : $elementCode =  $arr['subdes'];	break;
				
			}
			if(!$this->redefineTemplates){
				// Use default form general
				$replaceList = array(
					'{title}'		=>	$arr['title'],
					'{description}'	=> 	$arr['desc'],
					'{content}'		=>	$elementCode,
					'{key}'	=> 	$key,				
				);
				$cacheElement = $linesBlock ;	# new
				foreach($replaceList as $param => $value) 
					$cacheElement = str_replace($param,$value,$cacheElement);
				$linesCode .= $cacheElement;
			}
			else {
				// Use redefine form general
				$replaceList = array(
					'title'	=>	$arr['title'],
					'desc'	=> 	$arr['desc'],
					'form'	=>	$elementCode,
					'warnid'	=> 	'div_support_'.$key,				
				);
				foreach($replaceList as $param => $value) 
					$hredefcode = str_replace('{'.$key.'.'.$param.'}',$value,$hredefcode);
			}
		}
		
		 
		
		# Assign block to form
		$html = '' ;
		
		if($this->redefineTemplates){
			$html = $hredefcode;
		}else {
			$html = $this->formResource;	
			$html = preg_replace("#<!-- BOL - Header -->[\r\n]*(.*?)[\r\n]*<!-- EOL - Header -->#s",$warnBlock,$html);
			$html = preg_replace("#<!-- BOL - Lines -->[\r\n]*(.*?)[\r\n]*<!-- EOL - Lines -->#s",$linesCode,$html);
		} 
		
		
		# Replace form properties
		
		$html = str_replace('{submitJS}',$fname.'FormCheck()',$html);
		$html = str_replace('{action}',$faction,$html);
		$html = str_replace('{title}',$ftitle,$html);
		$submitbtn	=	$config['submit'];
		$html = str_replace('{submitbtn}',($submitbtn)?$submitbtn:'Gửi',$html);
		$html = str_replace('{style}',($config['style'])?$config['style']:' width :100% ',$html);
		$html = str_replace('{class}',($config['class'])?$config['class']:' ui-dialog ui-widget ui-widget-content ui-corner-all ',$html);
		$html = str_replace('{tbid}',($config['tableid'])?$config['tableid']:'defaultform',$html);		
		$submitbtn	=	$config['submit'];
		# Execute globalJS batch
		preg_match("#\/\/\/<!-CDB-FormFunction->[\r\n]*(.*?)[\r\n]*\/\/\/<!-CDE-FormFunction->#s",$this->jsResource,$cache);
		$JSform = str_replace('{form}',$fname,$cache[1]);
		$funcLine = '';
		foreach($this->jsElement as $jsFunc) {
			$funcLine .= $fname.$jsFunc.'() && ';
		}
		$JSform = str_replace('{functionlist}',$funcLine,$JSform);
		$this->globalJs = str_replace('{form}',$fname,$this->globalJs);
		$functionResource = preg_replace("#\/\/\/<!-CDB-ListFunction->[\r\n]*(.*?)[\r\n]*\/\/\/<!-CDE-ListFunction->#s",$this->globalJs,$this->jsResource);
		$functionResource = preg_replace("#\/\/\/<!-CDB-FormFunction->[\r\n]*(.*?)[\r\n]*\/\/\/<!-CDE-FormFunction->#s",$JSform,$functionResource);
		# Retur all source
		return $functionResource.$html;
	}
	
	function serverCheck(){
		return true;
	}


	# Get database data
	# @String <query>
	# ~ get all content and assign to class
	function getDBaseData($stringQuery){
		$q = $mysql->query($stringQuery);
		$r = $mysql->fetch_array($q);
		foreach ($this->input_array as $key=>$arr) $$key = (($r[$arr['table']]));
	}

	 
	
	
	
	# Get database data
	# @String <query>
	# ~ get all content and assign to class
	
	function createSQL($config_arr) {
		$inp_arr = $this->input_array ;
		if ($config_arr[0] == 'INSERT') {
			foreach ($inp_arr as $key=>$arr) {
				if (!$arr['table']) continue;
				$s1 .= '`'.$arr['table'].'`,';
				if ($arr['type'] == 'hidden_value')	$s2 .= '\"'.$arr['value'].'\",';
				else $s2 .= '\'$'.$key.'\',';
			}
			$s1 = substr($s1,0,-1);
			$s2 = substr($s2,0,-1);
			$sql = "INSERT INTO ".$config_arr[1]." (".$s1.") VALUES (".$s2.")";
		}
		elseif ($config_arr[0] == 'UPDATE') {
			foreach ($inp_arr as $key=>$arr) {
				global $$key;
				if (!$arr['table']) continue;
				if ($arr['update_if_true'] && !eval('return ('.$arr['update_if_true'].');')) continue;
				if ($arr['type'] == 'hidden_value' && !$arr['change_on_update']) continue;
				if ($arr['type'] == 'hidden_value')	$s1 .= $arr['table'].' = \''.$arr['value'].'\', ';
				else $s1 .= $arr['table'].' = \"$'.$key.'\", ';
			}
			$s1 = substr($s1,0,-2);
			if ($config_arr[2] && $config_arr[3]) $sql = "UPDATE ".$config_arr[1]." SET ".$s1." WHERE ".$config_arr[2]." = '\$".$config_arr[3]."'";
			else $sql = "UPDATE ".$config_arr[1]." SET ".$s1."";
		}
		return $sql;
	}
	
	
	function avaibleSubmit($menthod = "POST")
	{
		$rq_method = getenv('REQUEST_METHOD');
		//if ($rq_method != $menthod) return false;
		if($menthod=="POST")
		{
			if(!$_POST) return false;
		}
		//#FB::warn("$rq_method != $menthod");
		foreach($this->input_array as $key => $arr){
			if ($arr['null']) continue ;
			if (!$arr['type']) continue ;
			if ($arr['type'] == 'check') continue ;
			if ($menthod == "POST") {
				#FB::info($key . " => ".$_POST[$key]);
				if (!isset($_POST[$key])) {
					$this->hasError['str'] = 'Lỗi phần tử -> ' . $this->input_array[$key]['title'];
					#FB::info("Error avaible submit ".$this->hasError['str']);
					return false;
				}
			}
			else {
				if (!isset($_GET[$key]) || !$_GET[$key]) {
					$this->hasError['str'] = 'Lỗi phần tử -> ' . $this->input_array[$key]['title'];
					return false;
				}
			}
		}
		unset($this->hasError);
		return true ;
	}
	
	
	
	
	
	
	
	
	
	
	
	# eText - Text group
	# @String <keyname>
	# ~ Return element code and attack to globalJS javascript check , element : [text],[password],[textarea],[wysiwygeditor]
	function eText($key) {
		# Get elment information
		$element = $this->input_array[$key];
		$info = array();
		$info = $element ;
		
		###	@Create javascript part
		#
		# ConditionResource store all condition function javascript
		$conditioResource = '' ;
		# X1 create all element condition javascript function
		# All relation will create when this step passed
		if($element['null']!='true') 
			$conditioResource .= $this->genJSElementCheck('!$.trim(jsfobject.val())','Chưa nhập dữ liệu','null');
		if($info['max']) {
			$conditioResource .= $this->genJSElementCheck('isNaN(jsfobject.val())','Dữ liệu phải là số ','num');
			$conditioResource .= $this->genJSElementCheck('parseInt(jsfobject.val()) > '.$info['max'],'Dữ liệu không được lớn hơn '.$info['max'],'max');
		}
		if($info['min']) {
			$conditioResource .= $this->genJSElementCheck('isNaN(jsfobject.val())','Dữ liệu phải là số ','num');
			$conditioResource .= $this->genJSElementCheck('parseInt(jsfobject.val()) < '.$info['min'],'Dữ liệu không được nhỏ hơn '.$info['min'],'min');
		}
		if($info['number']) 
			$conditioResource .= $this->genJSElementCheck('isNaN(jsfobject.val())','Dữ liệu phải là số ','num');
		if($info['same']) 
			$conditioResource .= $this->genJSElementCheck('jsfobject.val() != '.$info['same'],'Mật khẩu nhập lại phải giống','num');
		# FunctionResource store function script
		$functionResource = ''; 
		# X2 create service function provinde check all relation
		preg_match("#\/\/\/<!-CDB-ListFunction->[\r\n]*(.*?)[\r\n]*\/\/\/<!-CDE-ListFunction->#s",$this->jsResource,$cache);
		$functionTemplates = $cache[1];
		$functionResource = preg_replace("#\/\/\/<!-CDB-ElementCheck->[\r\n]*(.*?)[\r\n]*\/\/\/<!-CDE-ElementCheck->#s",$conditioResource,$functionTemplates);
		# X3 assign element name for element
		$functionResource = str_replace('{key}',$key,$functionResource);
		### Completed general js check this element -> store to globalJS and arraylist function;
		$this->globalJs .=	$functionResource;
		$this->jsElement[$this->jsEIndex++] = $key."ObjecCheck";
		
		###	@Create html form part
		#
		
		switch ($element['type']) {
			case 'text' :
				$templates = '<input  class="text ui-widget-content ui-corner-all {class}"  name = "{name}" id = "{name}" onchange = "{onchange}" size = "{size}"
				style = "{style}" maxlength = "{maxlength}" value = "{value}" {distabled} {readonly} />
				';
			break;
			case 'password' :
				$templates = '<input type = "password" class="text ui-widget-content ui-corner-all {class}"  name = "{name}" id = "{name}" onchange = "{onchange}" size = "{size}"
				style = "{style}" maxlength = "{maxlength}" value = "" {distabled} {readonly} />
				';
			break;
			case 'time' :
				$templates = '
				
				<script type="text/javascript">
				$(function() {$("#{name}").datepicker({showButtonPanel: true},{});})
				</script>
				
				
				<input type = "text" class="text ui-widget-content ui-corner-all {class}"  name = "{name}" id = "{name}" onchange = "{onchange}" size = "{size}"
				style = "{style}" maxlength = "{maxlength}" value = "{value}" {distabled} {readonly} />
				';
			break;
			case 'textarea' : 
				$templates = '<textarea name = "{name}" rows="5" cols="47"  {distabled} {readonly} id = "{name}" class = "text ui-widget-content ui-corner-all  {class}"   style = "{style}" onchange = "{onchange}">{value}</textarea>';
			break;
			
			case 'wysiwyg3' : 
				$templates = '
				<input type = "button" value = "Ẩn / Hiện " onclick = "$(\'#divzas{name}\').slideToggle(300)">
				<div id = "divzas{name}" style="display:none">
				 <br><br>
				<textarea name = "{name}" rows="5" cols="50"  {distabled} {readonly} id = "{name}"  style = "{style}" class = "text ui-corner-all {class}"  onchange = "{onchange}">{value}</textarea>
				<script> 
					var edit1{name} = new InnovaEditor("edit1{name}");
						edit1{name}.REPLACE("{name}");
				</script>
				</div>
				';
			break;      
			
			case 'wysiwyg' : 
				if(file_exists("../FCKeditor/fckeditor_php5.php")){
					include_once("../FCKeditor/fckeditor_php5.php"); 
					$oFCKeditor = new FCKeditor('FCKeditor1') ;
					$oFCKeditor->BasePath = '../fckeditor/' ;
					$oFCKeditor->Config['SkinPath'] = $oFCKeditor->BasePath.'../editor/skins/silver/';
					$oFCKeditor->ToolbarSet = 'Default';
				}else {
					include_once("FCKeditor/fckeditor_php5.php"); 
					$oFCKeditor = new FCKeditor('FCKeditor1') ;
					$oFCKeditor->BasePath = 'fckeditor/' ;
					$oFCKeditor->Config['SkinPath'] = 'skins/silver/';
					$oFCKeditor->Config['LinkBrowser']=false;
					$oFCKeditor->Config['ImageBrowser']=false;
					$oFCKeditor->Config['FlashBrowser']=false;
					$oFCKeditor->Config['LinkUpload']=false;
					$oFCKeditor->Config['ImageUpload']=false;
					$oFCKeditor->Config['FlashUpload']=false;
					$oFCKeditor->ToolbarSet = 'UserDefault';
				}				
				$oFCKeditor->Value = '{value}' ;
				$oFCKeditor->InstanceName = '{name}';
				$oFCKeditor->Height = 400;
				
				$templates = '
				<input type = "button" value = "Ẩn / Hiện " onclick = "$(\'#divzas{name}\').slideToggle(300)">
				<div id = "divzas{name}" style="display:none;margin-top:5px;">';
				$templates .= $oFCKeditor->Create() ;
				$templates .= '</div>';
				
			break;
			
			case 'wysiwyg5' : 
				include_once("../jsframework/editor/cuteeditor_files/include_CuteEditor.php"); 
				$editor=new CuteEditor();
				$editor->ID=$key;
				//$editor->Text=($element['value'])?$element['value']:"Chưa cập nhật";
				if($element['value'])
					$editor->Text=$element['value'];
					
				$editor->EditorBodyStyle="font:normal 12px arial;";
				$editor->EditorWysiwygModeCss="php.css";
				$editor->Height = "400" ;
				$templates = '<button type="button" onclick = "$(\'#divzas{name}\').slideToggle(300)">Ẩn / Hiện </button><div id = "divzas{name}" style="display:;"><br><br>';
				$templates .= $editor->Draw();
				
				$templates .= '</div>';
				
				$templates .= '<script> 
					$(function(){
						$(\'#divzas{name}\').hide();
					});
				</script>';
				
			break;
			
			case 'wysiwyg4' : 
				//include_once("../jsframework/tinymce/tiny_mce/tiny_mce.js"); 
				//$templates = '<script type="text/javascript" src="../jsframework/tinymce/tiny_mce/tiny_mce.js">
				$templates = '<button type="button" onclick = "$(\'#divzas{name}\').slideToggle(300)">Ẩn / Hiện </button><div id = "divzas{name}" style="display:;"><br><br>';
				$templates .= '<textarea id="{name}" name="{name}" rows="15" cols="80" style="width: 50px">{value}</textarea>';
				$templates .= '<script> 
					tinyMCE.init({
						// General options
						mode : "exact",
						elements : "{name}",
						theme : "advanced",
						skin : "o2k7",
						plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups,autosave",
						theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
						theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
						theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
						theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft",
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "left",
						theme_advanced_statusbar_location : "bottom",
						theme_advanced_resizing : true,
						template_replace_values : {
							username : "Some User",
							staffid : "991234"
						}
					});
				</script>';
			break;
			
			case 'wysiwyg2' :
				$templates = '
				<input type = "button" value = "Ẩn / Hiện " onclick = "$(\'#divzas{name}\').slideToggle()">
				<div id = "divzas{name}" style="display:none">
				 <br><br>
				<textarea  name = "{name}" rows="5" cols="50"  {distabled} {readonly} id = "{name}"  style = "{style}" class = "text ui-corner-all {class}"  onchange = "{onchange}">{value}</textarea>
				<script> 
					 CKEDITOR.replace( \'{name}\',
					{
						
						customConfig  : \'config.js\' ,
					});
				</script>
				</div>
				';
			break;      
			
			case 'ajaxSF' :
				$templates = '
				<script type="text/javascript">
				$(function() {
						$("#{name}-fbrowse").fileTree({ root: "{urlroot}/", script: "index.php?ajax=serverfile" }, function(file) { 
						$("#{name}").val(file.replace("../",""));																										  
					})
				;})
				</script>
				
				<input type = "text" class="text ui-widget-content ui-corner-all {class}"  name = "{name}" id = "{name}" onchange = "{onchange}" size = "{size}"
				style = "{style}" maxlength = "{maxlength}" value = "{value}" {distabled} {readonly} />
				
				<input type = "button" value = "Danh sách file (Đóng / Mở)" onclick = "$(\'#{name}-fbrowse\').slideToggle(300)">
				<br><br>
				<div id = "{name}-fbrowse" style="display:none;">
				<div id="{name}-fbrowse">
				
				</div>
				</div>
				
				
				';
			break;
			
			
		}
		
		$html = str_replace('{name}',$key,$templates);
		$html = str_replace('{distabled}',($element['distable'])?'disabled="disabled"':'',$html);	
		$html = str_replace('{readonly}',($element['readonly'])?'readonly="readonly"':'',$html);
		$html = str_replace('{style}',$element['css'],$html);
		$html = str_replace('{class}',$element['class'],$html);
		$html = str_replace('{size}',($element['size'])?$element['size']:50,$html);
		$html = str_replace('{maxlength}',$element['length'],$html);
		$html = str_replace('{onchange}',$this->formname.$key.'ObjecCheck()',$html);
		$html = str_replace('{value}',htmlchars($element['value']),$html);
		$html = str_replace('{urlroot}',$element['root'],$html);		
		
		
		// $html .= '<div id = "div_support_'.$key.'"></div>';	
		
		# Return html code , javascript was stored in globalJS
		return $html;
	}
	
	
	
	
	
	
	function eTime($key){
		$script = '<script type="text/javascript">
	$(function() {
		$("#datepicker").datepicker({
			showButtonPanel: true
		},{dateFormat: "dd/mm/yyy"}
		);
	});
	</script>';
		$html = '<input type="text" size="30" id="datepicker" class="hasDatepicker"/>';
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	# eRadrio - Radio button
	# @String <keyname> @Array <list>[<value> => <title>]
	# ~ Return element code and attack to globalJS javascript check , element : [text],[password],[textarea],[wysiwygeditor]
	function eRadio($key) {
		# Get elment information
		$element = $this->input_array[$key];
		$list = array();
		$list = $element['list'];
		$html = '';
		
		$autoselect = true;
		
		if($element['value']){
			$valuex = $element['value'];
			# if value not comparate ! auto assign firt value
			//#FB::warn("$valuex = " .$valuex);
			foreach($list as $value){
				#FB::warn("-> $value = " .$value);
				if($valuex == $value){
					$autoselect = false;
					break;
				}
			}
		} 
		
		if($autoselect)	
			foreach($list as $value){
				$valuex = $value;
				break;
			}
			
		foreach($list as $title => $value){
			$i++;
			$html .= '<label style = "cursor:pointer" for = "'.$key.$i.'"><input type="radio" name="'.$key.'" id="'.$key.$i.'" value="'.$value.'" '. (($valuex == $value) ? 'checked="checked"' : ''). '/>'.$title.'</label>&nbsp;&nbsp;';
		}
		return $html;
	}
	
	function eIMGUpload($key) {
		$element = $this->input_array[$key];
		if( $element['value'] != "")
		{
			$code .= '<input class="text ui-widget-content ui-corner-all" size = "50" type="text" name="'.$key.'" id="'.$key.'" value = "'.$element['value'].'" /><span id="loadingz'.$key.'"></span><br />
			<p>
				<span id="eimgz384457'.$key.'">
				<img class = "ui-state-default ui-corner-all" src = "resize.php?url='.$element['value'].'&t=cut&width=100&height=100" />
				</span>
			</p>
			  <input class="text ui-widget-content ui-corner-all " border="0px"  id="imgbrowser_'.$key.'" name="imgbrowser_'.$key.'" size="30" value="" type="file" />';
		 }
		 else
		 {
			 $code .= '<input class="text ui-widget-content ui-corner-all " border="0px"  id="imgbrowser_'.$key.'" name="imgbrowser_'.$key.'" size="30" value="" type="file" />';
		 }
		$code = str_replace('{fileserver}',$element['fserver'],$code);	
		return $code;	
	}

	function eVIDEOUpload($key) {
		$element = $this->input_array[$key];
		if( $element['value'] != "")
		{
			$code .= '<input class="text ui-widget-content ui-corner-all" size = "50" type="text" name="'.$key.'" id="'.$key.'" value = "'.$element['value'].'" /><span id="loadingz'.$key.'"></span><br />
			<p>
			<input class="text ui-widget-content ui-corner-all " border="0px"  id="videobrowser_'.$key.'" name="videobrowser_'.$key.'" size="30" value="" type="file" />';
		}
		else
		{
			$code .= '<input class="text ui-widget-content ui-corner-all " border="0px"  id="videobrowser_'.$key.'" name="videobrowser_'.$key.'" size="30" value="" type="file" />';
		}
	
		$code = str_replace('{fileserver}',$element['fserver'],$code);	
		return $code;	
	}
		
	function eAttach($key) {
		$element = $this->input_array[$key];
		
		
		/*$code = "<script src='../jsframework/jquery.MultiFile.js'></script>";	
		$code .= "<div id='demo'></div>";
		$code .= "<script>
		$(function(){
			//$('#demo').append('fdsa');
			 $('#".$key."').MultiFile({
			  onFileSelect: function(element, value, master_element){
			   $('#demo').append('fdsa')
			  

			   //$('#attach_F1').attr('value','fdsafds')
			   //<input type=\"hidden\" name=\"strarray[]\" value=\"value\" />
			  }
			 }); 
		});
		</script>";	*/
		
		/*$code = "<script src='../jsframework/jquery.upload-1.0.2.js'></script>";	
		$code .= "<script>
		//$(function(){
			$('input[type=file]').change(function() {
				$(this).upload('..storage/mailattach/', function(res) {
					alert('File uploaded');
				}, 'json');
			});
			//});
		</script>";	*/
		
		$code = '<div id="file-uploader-demo1">		
			   
			</div>';
		
		$code .= "<div id='attach'></div>";
		$code .= '<link href="fileuploader.css" rel="stylesheet" type="text/css">';
		$code .= '<script src="fileuploader.js" type="text/javascript"></script>';
    	$code .= '<script>        
			function createUploader(){            
            var uploader = new qq.FileUploader({
                element: document.getElementById("file-uploader-demo1"),
                action: "php.php",
				params: {
					folder: "../storage/mailattach"
				},
            });           
        }
        
        window.onload = createUploader;     
		</script>';
		
		  
	$code = str_replace('{fileserver}',$element['fserver'],$code);	
	return $code;	
		 
	}
	
	
	
	
	
	# eSelect - Select button
	# @String <keyname> @Array <list>[<value> => <title>]
	# ~ Return element code and attack to globalJS javascript check , element : [text],[password],[textarea],[wysiwygeditor]
	function eSelect($key) {
		# Get elment information
		/*$element = $this->input_array[$key];
		$list = array();
		$list = $element['list'];
		$html = '';
		
		$autoselect = true;
		
		if($element['value']){
			$valuex = $element['value'];
			# if value not comparate ! auto assign firt value
			#FB::warn("$valuex = " .$valuex);
			foreach($list as $value){
				#FB::warn("-> $value = " .$value);
				if($valuex == $value){
					$autoselect = false;
					break;
				}
			}
		}
		
		
		if($autoselect) {
			if($list){
				foreach($list as $value){
					$valuex = $value;
					break;
				}
			}
		}*/
		
		// If value not avaible in select
		# Get elment information
		
		$element = $this->input_array[$key];
		$list = array();
		$list = $element['list'];
		$html = '';
		if($element['value'])
			$valuex = $element['value'];
		else	
			if($list)
			foreach($list as $value){
				$valuex = $value;
				break;
			}
		
		$html = '<select class="text ui-widget-content ui-corner-all " name="'.$key.'" id="'.$key.'">';	
		if($list)
		foreach($list as $title => $value){
			$html .= '<option value="'.$value.'" '. (($valuex == $value) ? 'selected="selected"' : ''). '/>'.$title.'</option>';
		}
		$html .= '</select>';
		return $html;
	}
	
	
	
	function eTextauto($key) {
		
		$element = $this->input_array[$key];
		$code = '<input id="'.$key.'" />';
		
		//$code .= "<div id='attach'></div>";
		//$code .= '<link href="fileuploader.css" rel="stylesheet" type="text/css">';
		/*$code .= '<script src="fileuploader.js" type="text/javascript"></script>';*/
		$code .= '<script language="javascript" src="../jsframework/jquery.ui.autocomplete.js"></script>';
    	$code .= '<script>        
			function createUploader(){            
            var uploader = new qq.FileUploader({
                element: document.getElementById("file-uploader-demo1"),
                action: "php.php",
				params: {
					folder: "../storage/mailattach"
				},
            });           
        }
        
        window.onload = createUploader;     
		</script>';
		
		  
	$code = str_replace('{fileserver}',$element['fserver'],$code);	
	return $code;
	}
	
	 
	
	
	
	# eSelect - Select button
	# @String <keyname> @Array <list>[<value> => <title>]
	# ~ Return element code and attack to globalJS javascript check , element : [text],[password],[textarea],[wysiwygeditor]
	function eCheck($key) {
		# Get elment information
		$element = $this->input_array[$key];
		$info = $element['info'];
		$html = '<input value = "1" '.(($element['value'])?' checked':'').' type = "checkbox" name = "'.$key.'" id = "'.$key.'">'.$element['subdes'];
		return $html;
	}
	
	 
	
	
	
	# general javascript function
	# this function return preg script for 1 relation of element
	function genJSElementCheck($condition,$errormsg,$erricon){		
		# Get element check templates
		preg_match("#\///<!-CDB-ElementCheck->[\r\n]*(.*?)[\r\n]*///<!-CDE-ElementCheck->#s",$this->jsResource,$cache);
		$elementTemplates = $cache[1];
		 
		# It will have containt
		
		/*
				if( {condition} )
				{
					jsElementError(jsfobject,\'{messenger}\');
					return false;
				}
				else 
					jsElementReset(jsfobject,\'{messenger}\');				
				}

		*/
		$elementTemplates = str_replace('{condition}',$condition,$elementTemplates);
		//die(str_replace('{messenger}',$errormsg,$elementTemplates));
		return str_replace('{messenger}',$this->icons[$erricon].$errormsg,$elementTemplates);
	}
	
	
	function setErrorString($str){
		$this->hasError['str'] = $str;
	}
	
	
	
	
}
?>

